package org.llc.user.service;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.llc.common.model.UserInfoDTO;
import org.llc.common.model.Result;
import org.llc.user.enums.CheckEnum;
import org.llc.user.dao.UserInfoMapper;
import org.llc.user.entity.UserInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 用户信息服务实现类
 *
 * @author llc
 * @date 2021-04-18
 * @since 1.0.0
 */
@Slf4j
@Service
public class UserInfoService {


    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private Snowflake snowflake;

    /**
     * TODO 分布式事务
     */
    public Result init(UserInfoDTO userInfoDTO) {

        Long accountId = userInfoDTO.getAccountId();
        String nickname = userInfoDTO.getNickname();
        String sex = userInfoDTO.getSex();
        String headPortrait = userInfoDTO.getHeadPortrait();

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        UserInfo existing = userInfoMapper.selectOne(queryWrapper);

        if (null != existing) {
            return Result.failed(CheckEnum.USER_ID_ALREADY_EXIST.getCode(), CheckEnum.USER_ID_ALREADY_EXIST.getMsg());
        }

        UserInfo userInfo = new UserInfo();
        userInfo.setId(snowflake.nextId());
        userInfo.setAccountId(accountId);
        userInfo.setNickname(StringUtils.isNotEmpty(nickname) ? nickname : "昵称" + RandomUtil.randomInt(100000, 999999));
        userInfo.setSex(StringUtils.isNotEmpty(sex) ? sex : "F");
        userInfo.setHeadPortrait(StringUtils.isNotEmpty(headPortrait) ? headPortrait : null);
        userInfo.setCreateTime(LocalDateTime.now());
        userInfoMapper.insert(userInfo);

        log.info("用户信息初始化完成 accountId -> {} ", accountId);
        return Result.succeed();
    }

    public List<UserInfo> list() {
        return userInfoMapper.selectUser();
    }
}
